function findLoopEndIndex(s, begin) {
    for (var i = begin + 1; i < s.length; i++) {
        if (s[i] === 'E') {
            var temp = s.slice(begin, i + 1).replace(/[^EW]/g, '');
            if (/W+E+/.test(temp) && temp.match(/E/g).length === temp.match(/W/g).length)
                return i;
        }
    }
}
function poohbear(tape) {
    tape = tape.replace(/[^+\-<>cpWEPNTQULIVABYD]/g, '')
    var p = 0;
    var mems = []
    var copied = null;
    var out = []
    var loops = []
    for (var i = 0; i < tape.length; i++) {
        var code = tape[i];
        if (!mems[p]) mems[p] = 0;
        switch (code) {
            case '+': if (!mems[p]) mems[p] = 0; mems[p] = (mems[p] + 1) % 256; break;
            case '-': if (!mems[p]) mems[p] = 0; mems[p] = mems[p] ? mems[p] - 1 : 255; break;
            case '>': p++; if (!mems[p]) mems[p] = 0; break;
            case '<': p--; if (!mems[p]) mems[p] = 0; break;
            case 'c': copied = mems[p]; break;
            case 'p': mems[p] = copied; break;
            case 'W'://while loop:While loop - While the current cell is not equal to 0
                if (mems[p] > 0) loops.push(i); else i = findLoopEndIndex(tape, i); break;
            case 'E'://Closing character for loops
                if (mems[p] > 0) i = loops[loops.length - 1]; else loops.pop(); break;
            case 'P': out.push(String.fromCharCode(mems[p])); break;
            case 'N': out.push(mems[p]); break;
            case 'T': mems[p] = (2 * mems[p]) % 256; break;
            case 'Q': mems[p] = (mems[p] ** 2) % 256; break;
            case 'U': mems[p] = parseInt(mems[p] ** 0.5); break;
            case 'L': mems[p] = (mems[p] + 2) % 256; break;
            case 'I': mems[p] -= 2; if (mems[p] < 0) mems[p] += 256; break;
            case 'V': mems[p] = parseInt(mems[p] / 2); break;
            case 'A': mems[p] = (mems[p] + copied || 0) % 256; break;
            case 'B': mems[p] -= copied || 0; if (mems[p] < 0) mems[p] += 256; break;
            case 'Y': mems[p] = (mems[p] * (copied || 1)) % 256; break;
            case 'D': mems[p] = parseInt(mems[p] / copied); break;
        }
    }
    return out.join('');
}
